using AutoMapper;
using Microsoft.EntityFrameworkCore;
using ShopForWeb.Dto.ViewModels;
using ShopForWeb.Models;

namespace ShopForWeb.Service;
public class OrderService
{
  private ShopDbContext _context;
  private IMapper _map;
  public OrderService(ShopDbContext context, IMapper map)
  {
    _context = context;
    _map = map;
  }
  //添加
  public async Task<int> AddNewOrderAsync(int userID, List<OrderDetailViewModel> odvms)
  {
    if (odvms.Count == 0)
      return 0;
    //处理生成订单
    Order o = new Order()
    {
      OrderID = System.Guid.NewGuid().ToString("N"),
      UserID = userID,
      OrderState = 0,
      ManagerID = 1,
      OwnOrderDetails = _map.Map<List<OrderDetails>>(odvms)
    };
    // 处理订单详情
    // _context.Entry(o).State = EntityState.Added;
    var ods = _map.Map<List<OrderDetails>>(odvms);
    foreach (var item in ods)
    {
      item.OrderID = o.OrderID;
      _context.Entry(item).State = EntityState.Added;
      o.Price += item.Price * item.Sales;
    }
    return await _context.SaveChangesAsync();
  }
}
